package com.homer.commons.sscpprotocol.server.base;

import java.nio.ByteOrder;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.demux.MessageDecoder;
import org.apache.mina.filter.codec.demux.MessageDecoderResult;

public abstract class AbstractMessageDecoder implements MessageDecoder {
    private boolean bigEndian = true;

    public final int version;

    protected AbstractMessageDecoder(int version) {
        this.version = version;
    }

    public void setBigEndian(boolean bigEndian) {
        this.bigEndian = bigEndian;
    }

    public MessageDecoderResult decodable(IoSession session, IoBuffer in) {
        if (this.bigEndian)
            in.order(ByteOrder.BIG_ENDIAN);
        else {
            in.order(ByteOrder.LITTLE_ENDIAN);
        }

        if (in.remaining() < version) {
            return MessageDecoderResult.NEED_DATA;
        }

        //int count = in.getInt();
//        if (this.version >= in.getInt()) {
//            return MessageDecoderResult.OK;
//        }
//
//        return MessageDecoderResult.NOT_OK;
        
        return MessageDecoderResult.OK;
    }

    public MessageDecoderResult decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
        AbstractMessage message = decodeMessage(session, in);

        if (message == null) {
            return MessageDecoderResult.NEED_DATA;
        }
        out.write(message);

        return MessageDecoderResult.OK;
    }

    protected abstract AbstractMessage decodeMessage(IoSession paramIoSession, IoBuffer paramIoBuffer);
}
